﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace StateDemo
{
    public sealed partial class MainPage : Page
    {
        enum Strategy { Settings, File }
        Strategy STRATEGY = Strategy.File;

        public MainPage()
        {
            this.InitializeComponent();
            App.Current.Suspending += Current_Suspending;
            Loaded += MainPage_Loaded;
        }

        async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                switch (STRATEGY)
                {
                    case Strategy.Settings:
                        // load from setting
                        this.TextBox1.Text = Windows.Storage.ApplicationData.Current.LocalSettings.Values["MyData"].ToString();
                        break;

                    case Strategy.File:
                        // load from file
                        var _Folder = Windows.Storage.ApplicationData.Current.LocalFolder;
                        var _File = await _Folder.GetFileAsync("state.txt");
                        this.TextBox1.Text = await Windows.Storage.FileIO.ReadTextAsync(_File);
                        break;
                }
            }
            catch { /* no data */ }
        }

        async void Current_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
        {
            switch (STRATEGY)
            {
                case Strategy.Settings:
                    // save to setting
                    Windows.Storage.ApplicationData.Current.LocalSettings.Values["MyData"] = this.TextBox1.Text;
                    break;

                case Strategy.File:
                    // save to file
                    var _Deferral = e.SuspendingOperation.GetDeferral();
                    var _Folder = Windows.Storage.ApplicationData.Current.LocalFolder;
                    var _File = await _Folder.CreateFileAsync("state.txt", Windows.Storage.CreationCollisionOption.OpenIfExists);
                    await Windows.Storage.FileIO.WriteTextAsync(_File, this.TextBox1.Text);
                    _Deferral.Complete();
                    break;
            }
        }
    }
}
